#include <stdio.h>

typedef struct cpu_occupy         //定义一个cpu occupy的结构体
{
    char name[20];      // 第一列 一般是 "cpu"
    unsigned int user; // 从系统启动开始累计到当前 用户态CPU时间，单位(jiffies)
    unsigned int nice; // 从系统启动到当前，nice值为负的进程所占用CPU时间
    unsigned int system; // 内核占用时间
    unsigned int idle; // 除硬盘IO等待以外的其他等待时间
    unsigned int iowait; // 硬盘IO等待时间
    unsigned int irq; // 硬中断时间
    unsigned int softirq;  // 软中断时间
} CPU_OCCUPY;

typedef struct mem_occupy         //定义一个mem occupy的结构体
{
    char name[20];      //定义一个char类型的数组名name有20个元素
    unsigned long total;
    char name2[20];
    unsigned long free;
} MEM_OCCUPY;

int get_memoccupy(MEM_OCCUPY *mem) //对无类型get函数含有一个形参结构体类弄的指针O
{
    FILE *fd;
    int n;
    char buff[256];
    MEM_OCCUPY *m;
    m = mem;

    fd = fopen("/proc/meminfo", "r");
    if (fd == NULL)
        return -1;

    fgets(buff, sizeof(buff), fd);
    sscanf(buff, "%s %u", m->name, &m->total);

    fgets(buff, sizeof(buff), fd); //从fd文件中读取长度为buff的字符串再存到起始地址为buff这个空间里
    sscanf(buff, "%s %u", m->name2, &m->free);

    fclose(fd);     //关闭文件fd

    return 0;
}

int get_cpuoccupy(CPU_OCCUPY *cpust) //对无类型get函数含有一个形参结构体类弄的指针O
{
    FILE *fd;
    int n;
    char buff[256];
    CPU_OCCUPY *cpu_occupy;
    cpu_occupy = cpust;

    fd = fopen("/proc/stat", "r");
    fgets(buff, sizeof(buff), fd);

    sscanf(buff, "%s %u %u %u %u", cpu_occupy->name, &cpu_occupy->user,
            &cpu_occupy->nice, &cpu_occupy->system, &cpu_occupy->idle);

    fclose(fd);
    return 0;
}

int cal_cpuoccupy(CPU_OCCUPY *o, CPU_OCCUPY *n)
{
    unsigned long od, nd;
    unsigned long id, sd;
    int cpu_use = 0;

    od = (unsigned long) (o->user + o->nice + o->system + o->idle); //第一次(用户+优先级+系统+空闲)的时间再赋给od
    nd = (unsigned long) (n->user + n->nice + n->system + n->idle); //第二次(用户+优先级+系统+空闲)的时间再赋给od

    id = (unsigned long) (n->user - o->user);    //用户第一次和第二次的时间之差再赋给id
    sd = (unsigned long) (n->system - o->system);    //系统第一次和第二次的时间之差再赋给sd
    if ((nd - od) != 0)
        cpu_use = (int) ((sd + id) / (nd - od) * 100); //((用户+系统)乘100)除(第一次和第二次的时间差)再赋给g_cpu_used
    else
        cpu_use = 0;
    printf("cpu: %u%%\n", cpu_use);
    return cpu_use;
}

int main()
{
    CPU_OCCUPY cpu_stat1;
    CPU_OCCUPY cpu_stat2;
    MEM_OCCUPY mem_stat;
    int cpu;

    //获取内存
    get_memoccupy((MEM_OCCUPY *) &mem_stat);
    printf("mem total: %d, free: %d\n", mem_stat.total, mem_stat.free);

    //第一次获取cpu使用情况
    get_cpuoccupy((CPU_OCCUPY *) &cpu_stat1);
    sleep(10);

    //第二次获取cpu使用情况
    get_cpuoccupy((CPU_OCCUPY *) &cpu_stat2);

    //计算cpu使用率
    cpu = cal_cpuoccupy((CPU_OCCUPY *) &cpu_stat1, (CPU_OCCUPY *) &cpu_stat2);

    return 0;
}
